<?php

/**
 * This is the model class for table "tbl_user".
 *
 * The followings are the available columns in table 'tbl_user':
 * @property integer $user_id
 * @property string $email
 * @property string $password
 * @property string $firstname
 * @property string $lastname
 * @property integer $gender
 * @property integer $birthday
 * @property string $passport
 * @property string $address
 * @property string $city
 * @property string $mobile
 * @property integer $status
 * @property string $permission
 * @property string $signup
 * @property string $lastlogin
 *
 * The followings are the available model relations:
 * @property Customer[] $customers
 */
class User extends CActiveRecord
{
    public $old_password;
    public $new_password;
    public $repeat_password;
    
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'tbl_user';
	}
    
    /**
    *@return boolean permission
    */
    public function isView(){
        $permission=User::model()->getPermission();
        if(count($permission)>1){
            if(in_array('Xem',$permission)){
                return true;
            }else{
                return false;
            }   
        }elseif(count($permission)==1){
            if(strstr($permission,'Xem')){
                return true;
            }else{
                return false;
            }   
        }
    }
    
    /**
    *@return boolean permission
    */
    public function isCreate(){
        $permission=User::model()->getPermission();
        if(count($permission)>1){
            if(in_array('Thêm',$permission)){
                return true;
            }else{
                return false;
            }   
        }
    }
    
    /**
    *@return boolean permission
    */
    public function isUpdate(){
        $permission=User::model()->getPermission();
        if(count($permission)>1){
            if(in_array('Sửa',$permission)){
                return true;
            }else{
                return false;
            }   
        }
    }
    
    /**
    *@return boolean permission
    */
    public function isDel(){
        $permission=User::model()->getPermission();
        if(count($permission)>1){
            if(in_array('Xoá',$permission)){
                return true;
            }else{
                return false;
            }   
        }
    }
    
    /**
    *@return boolean permission
    */
    public function isAdmin(){
        $permission=User::model()->getPermission();
        if(count($permission)>1){
            if(in_array('Quản trị',$permission)){
                return true;
            }else{
                return false;
            }   
        }
    }
    
    /**
    *@return boolean superadmin chuvantu@gmail.com
    */
    public function isSuperAdmin(){
        if(Yii::app()->user->getId()=="chuvantu@gmail.com"){
            return true;
        }else{
            return false;
        }
    }
    
    /**
    *@return update lastlogin field of user
    */
    public function lastLogin($email){
        return Yii::app()->db->createCommand('UPDATE tbl_user SET lastlogin=NOW() WHERE email="'.$email.'"')->execute();
    }
    
    /**
    *@return int user_id
    */
    public function getId($email){
        $user=User::model()->findByAttributes(array('email'=>$email));
        return $user['user_id'];
    }
    
    /**
    *@return string password of current user
    */
    public function getPassword()
    {
        $user = User::model()->findByAttributes(array('email'=>Yii::app()->user->getId()));
        return $user['password'];
    }
    
    /**
    *@return string email of current user
    */
    public function getEmail()
    {
        $user = User::model()->findByAttributes(array('email'=>Yii::app()->user->getId()));
        return $user['email'];
    }
    
    /**
    *@return array string permission of current user
    */
    public function getPermission()
    {
        $user = User::model()->findByAttributes(array('email'=>Yii::app()->user->getId()));
        if(strstr($user['permission'],';')){
            $permission=explode(';',$user['permission']);
            foreach ($permission as $perm) {
                $permissionName[]=Permission::model()->getPermissionName($perm);
            }
            return $permissionName;  
        }elseif(strlen($user['permission'])==1){
            return Permission::model()->getPermissionName($user['permission']);
        }
    }
    
    /**
    *
    */        

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('email, password', 'required','message'=>REQUIRED_NOT_NULL),
            array('email','email','message'=>IS_EMAIL),
            array('email','unique','message'=>'Email đã tồn tại'),
			array('gender, birthday, status', 'numerical', 'integerOnly'=>true),
			array('email, passport, permission', 'length', 'max'=>255),
			array('firstname, lastname', 'length', 'max'=>16),
			array('city', 'length', 'max'=>15),
			array('mobile', 'length', 'max'=>11),
			array('address, signup, lastlogin', 'safe'),
            array('old_password,new_password,repeat_password','required','message'=>REQUIRED_NOT_NULL),
            array('repeat_password','compare','compareAttribute'=>'new_password','message'=>'Mật khẩu không trùng khớp'),  
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('user_id, email, password, firstname, lastname, gender, birthday, passport, address, city, mobile, status, permission, signup, lastlogin', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'customers' => array(self::HAS_MANY, 'Customer', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'user_id' => 'Mã',
			'email' => 'Email',
			'password' => 'Mật khẩu',
			'firstname' => 'Tên',
			'lastname' => 'Họ đệm',
			'gender' => 'Giới tính',
			'birthday' => 'Sinh nhật',
			'passport' => 'CMND/Hộ chiếu',
			'address' => 'Địa chỉ',
			'city' => 'Thành phố',
			'mobile' => 'Điện thoại',
			'status' => 'Trạng thái',
			'permission' => 'Quyền',
			'signup' => 'Đăng ký',
			'lastlogin' => 'Đăng nhập lần cuối',
            'old_password'=>'Mật khẩu cũ',
            'new_password'=>'Mật khẩu mới',
            'repeat_password'=>'Nhập lại mật khẩu',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;
                        
		$criteria->compare('user_id',$this->user_id);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('firstname',$this->firstname,true);
		$criteria->compare('lastname',$this->lastname,true);
		$criteria->compare('gender',$this->gender);
		$criteria->compare('birthday',$this->birthday);
		$criteria->compare('passport',$this->passport,true);
		$criteria->compare('address',$this->address,true);
		$criteria->compare('city',$this->city,true);
		$criteria->compare('mobile',$this->mobile,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('permission',$this->permission,true);
		$criteria->compare('signup',$this->signup,true);
		$criteria->compare('lastlogin',$this->lastlogin,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return User the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
}
